//
//  ForgotView.m
//  Bespoke
//
//  Created by 郭 俊佑 on 12/10/3.
//
//

#import "ForgotPassWord.h"
#import "RequestAPIFunction.h"

#define ForgotPassword_API @"http://54.235.166.43/BeSpokeAPI/Email/ForgotPassword.php"

@implementation ForgotPassWord
@synthesize Tf_Email;
@synthesize delegate;

- (IBAction)CancelPressed:(id)sender {
    [delegate CancelPressed_ForgotPassWord];
}

- (IBAction)SendEmailPressed:(id)sender {
    
    if (([Tf_Email.text isEqualToString:@""])||(Tf_Email.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Email." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if ([Tf_Email.text rangeOfString:@"@"].location == NSNotFound) {//Check username is or not Email.
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter a valid email address." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:ForgotPassword_API]];
    [request setHTTPMethod:@"POST"];
    
    NSMutableData *postBody = [NSMutableData data];
    [postBody appendData:[[NSString stringWithFormat:@"Email=%@",Tf_Email.text] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postBody];
    
    NSError *ErrMSG = [NSError alloc];
    //get response
    NSHTTPURLResponse* urlResponse = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&ErrMSG];
    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
    if ([result rangeOfString:@"Message sent!"].location != NSNotFound) {
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Password sent!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
    }
    else if ([result rangeOfString:@"The Email you entered is incorrect."].location != NSNotFound) {
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"We don't have this email in our system." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
    }
    else {
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:result delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self SendEmailPressed:textField];
    return YES;
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    [self.delegate EmailSuccess];
}

@end
